from rest_framework import serializers
from django_redis import get_redis_connection
from rest_framework.response import Response

from goods.models import SKU
from drf_haystack.serializers import HaystackSerializer

from goods.search_indexes import SKUIndex
from orders.models import OrderGoods


class CategoriesListSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = '__all__'


class SKUSearchSerializer(HaystackSerializer):
    object = CategoriesListSerializer()

    class Meta:
        index_classes = [SKUIndex]
        fields = ['text', 'object']


class SKUHistorSerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1)

    def validate(self, attrs):
        try:
            SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('该商品不存在')
        return attrs

    def create(self, validated_data):
        user = self.context['request'].user
        conn = get_redis_connection('history')

        conn.lrem('history_%s' % user.username, 0, self.validated_data['sku_id'])

        conn.lpush('history_%s' % user.username, self.validated_data['sku_id'])

        conn.ltrim('history_%s' % user.username, 0, 4)

        return validated_data


# class CommentsListSerializer(serializers.ModelSerializer):
#
#     class Meta:
#         model = OrderGoods
#         fields = '__all__'
#         extra_kwargs = {
#             'comment': {
#                 'max_length': 120,
#                 'min_length': 1
#             }
#         }
#
#     def update(self, instance, validated_data):
#         OrderGoods.objects.update(
#             {
#                 instance['comment']: validated_data['comment'],
#                 instance['score']: validated_data['score'],
#                 instance['is_commented']: validated_data['is_commented'],
#                 instance['is_anonymous']: validated_data['is_anonymous'],
#
#             }
#         )
#         return Response({'massage': 'ok'})



